package com.tjj.demo.springboot.es.controller;

import com.alibaba.fastjson.JSON;
import com.tjj.demo.springboot.es.entity.Blog;
import com.tjj.demo.springboot.es.entity.EsBlog;
import com.tjj.demo.springboot.es.repository.BlogESRepository;
import com.tjj.demo.springboot.es.repository.BlogJPARepository;
import lombok.Data;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private BlogJPARepository blogJPARepository;
    @Autowired
    private BlogESRepository blogESRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @RequestMapping("/")
    public String index(){
        return "index.html";
    }

    @ResponseBody
    @GetMapping("/blogs")
    public List<Blog> getBlogs(){
        return blogJPARepository.findAll();
    }

    @ResponseBody
    @GetMapping("/blog/{id}")
    public Blog getBlog(@PathVariable Integer id){
        return blogJPARepository.findById(id).get();
    }

    @ResponseBody
    @PostMapping("/search")
    public Object search(@RequestBody QueryModel qm){
        Map<String, Object> result = new HashMap<>();
        StopWatch sw = new StopWatch();
        sw.start();
        if("mysql".equals(qm.getType())){
            result.put("list", blogJPARepository.searchByMysql(qm.getKeyword()));
        }else if("es".equals(qm.getType())){
            //若索引不存在
            if(!elasticsearchTemplate.indexExists(EsBlog.class)){
                //创建索引
                elasticsearchTemplate.createIndex(EsBlog.class);
                List<Blog> list = blogJPARepository.findAll();

                //将MySQL数据插入到ES
                if(!CollectionUtils.isEmpty(list)){
                    List<EsBlog> esList = JSON.parseArray(JSON.toJSONString(list), EsBlog.class);
                    blogESRepository.saveAll(esList);
                }
            }
            //搜索ES数据
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            builder.should(QueryBuilders.matchPhraseQuery("title", qm.keyword));
            builder.should(QueryBuilders.matchPhraseQuery("content", qm.keyword));

            System.out.println(builder.toString());

            Page<EsBlog> page = (Page<EsBlog>) blogESRepository.search(builder);

            List<EsBlog> blogs = page.getContent();
            result.put("list", blogs);

        }
        sw.stop();
        result.put("duration", sw.getTotalTimeMillis());
        return result;
    }

    @Data
    public static class QueryModel{
        private String type;
        private String keyword;
    }
}
